import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/login', component: () => import('@/views/Login/LoginPage.vue') },
    {
      path: '/',
      component: () => import('@/views/Layout/LayoutPage.vue'),
      redirect: () => {
        {
          if (useUserStore().power === 1) {
            return '/arrangeduty'
          }
          if (useUserStore().power === 0) {
            return '/stu/arrangeduty'
          }
          return '/login'
        }
      },
      children: [
        {
          path: '/arrangeduty',
          component: () => import('@/views/ArrangeDuty/ArrangeDutyPage.vue')
        },
        {
          path: '/arrangeduty/person',
          component: () => import('@/views/PersonManage/PersonManagePage.vue')
        },
        {
          path: '/knowledgelibrary',
          component: () => import('@/views/KnowledgeLibrary/KnowledgeLibraryPage.vue')
        },
        {
          path: '/stu/arrangeduty',
          component: () => import('@/views/ArrangeDuty/stu_ArrangeDutyPage.vue')
        },
        {
          path: '/stu/knowledgelibrary',
          component: () => import('@/views/KnowledgeLibrary/stu_KnowledgeLibraryPage.vue')
        }
      ]
    }
  ]
})

// 拦截
router.beforeEach((to) => {
  if (!useUserStore().token && to.path !== '/login') {
    ElMessage.error('未登录')
    return '/login'
  }
  if (
    useUserStore().power === 0 &&
    to.path !== '/stu/arrangeduty' &&
    to.path !== '/stu/knowledgelibrary' &&
    to.path !== '/login'
  ) {
    ElMessage.error('权限错误')
    return '/login'
  }
})

export default router
